use wasm_bindgen::{prelude::*,JsValue,Clamped};
use web_sys::{OffscreenCanvas, ImageBitmap,ImageData,OffscreenCanvasRenderingContext2d,Blob};
use wasm_bindgen_futures::{future_to_promise,JsFuture};
use js_sys::Promise;
/*fn log(s: &str) {
    web_sys::console::log_1(&JsValue::from_str(s));
}*/

#[wasm_bindgen]
pub fn generate_alpha_png(img: &ImageBitmap, return_as_blob: bool) -> Promise {//Result<ImageBitmap, JsValue> {
    // 获取 ImageBitmap 的宽度和高度
    let width = img.width();
    let height = img.height();

    // 创建原始图像 Canvas
    let canvas = OffscreenCanvas::new(width, height).unwrap();
    // log("enter");
    let ctx = canvas.get_context("2d").unwrap().unwrap().dyn_into::<OffscreenCanvasRenderingContext2d>().unwrap();
    // log("hello");
    // 创建输出图像 Canvas
    let out_width = width * 2;
    let out_canvas = OffscreenCanvas::new(out_width, height).unwrap();
    let out_ctx = out_canvas.get_context("2d").unwrap().unwrap().dyn_into::<OffscreenCanvasRenderingContext2d>().unwrap();

    // 绘制原始图像到原始 Canvas
    ctx.draw_image_with_image_bitmap(img, 0.0, 0.0).unwrap();

    // 填充输出 Canvas 背景为黑色
    out_ctx.set_fill_style(&JsValue::from_str("black"));
    out_ctx.fill_rect(0.0, 0.0, out_width as f64, height as f64);

    // 获取整个 Canvas 的图像数据
    let image_data = ctx.get_image_data(0.0, 0.0, width as f64, height as f64).unwrap();
    let mut data = image_data.data();
    
    // 创建 Alpha 通道图像数据
    for i in (0..data.len()).step_by(4) {
        data[i] = 255; // R
        data[i + 1] = 255; // G
        data[i + 2] = 255; // B
        // data[i + 3]不变，保持Alpha通道的值
    }
    // 将 Alpha 数据放入 Alpha Canvas
    let alpha_image_data = ImageData::new_with_u8_clamped_array_and_sh(Clamped(&mut data), width, height).unwrap();
    // 将 Alpha 数据放入 Alpha Canvas
    ctx.put_image_data(&alpha_image_data, 0.0, 0.0).unwrap();

    // 绘制 Alpha Canvas 到左半部分
    out_ctx.draw_image_with_offscreen_canvas(&canvas, 0.0, 0.0).unwrap();

    // 绘制原始 Canvas 到右半部分
    out_ctx.draw_image_with_image_bitmap(&img, width as f64, 0.0).unwrap();
    future_to_promise(async move {
        if return_as_blob {
            let bitmap = JsFuture::from(out_canvas.convert_to_blob().unwrap()).await?.dyn_into::<Blob>().unwrap();
            Ok(JsValue::from(bitmap))
        } else {
            // 将输出 Canvas 转换为 ImageBitmap 并返回
            let bitmap = out_canvas.transfer_to_image_bitmap().unwrap();
            Ok(JsValue::from(bitmap))
        }
    })
}